import { computed, onMounted, ref } from "vue";
import { ElMessageBox } from "element-plus";
import { useDialog } from "@/composables/useDialog";
import { useListPage } from "@/composables/useListPage";
import { message } from "@/utils/message";
import productApi, {
  type ProductListItem,
  type ProductListParams,
  PRODUCT_STATUS_MAP,
  PRODUCT_AUDIT_STATUS_MAP
} from "@/api/system/product/product";
import { fetchRegionTree } from "@/api/system/region/region";

interface ProductFilterForm {
  keyword: string;
  status: string | number;
  audit_status: string | number;
  category_id: string | number;
  brand_id: string | number;
  seller_org_id: string;
}

const DEFAULT_FILTER: ProductFilterForm = {
  keyword: "",
  status: "",
  audit_status: "",
  category_id: "",
  brand_id: "",
  seller_org_id: ""
};

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "草稿", value: 0 },
  { label: "上架", value: 1 },
  { label: "下架", value: 2 },
  { label: "禁用", value: 3 }
];

const AUDIT_STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "待审核", value: 0 },
  { label: "已通过", value: 1 },
  { label: "已驳回", value: 2 }
];

const mapCategoryOptions = (tree: Array<any>, parentLabel = ""): any[] => {
  return tree.map(node => {
    const label = node.name ?? "";
    const currentLabel = parentLabel ? `${parentLabel} / ${label}` : label;
    const option: any = {
      id: node.id,
      label: currentLabel,
      value: node.id
    };
    if (Array.isArray(node.children) && node.children.length > 0) {
      option.children = mapCategoryOptions(node.children, currentLabel);
    }
    return option;
  });
};

export function useProductList() {
  const { openDialog } = useDialog();

  const brandOptions = ref<Array<{ id: number; name: string; slug?: string }>>(
    []
  );
  const categoryTree = ref<Array<any>>([]);
  const regionTree = ref<Array<any>>([]);

  const {
    formState,
    pagination,
    dataList,
    loading,
    multipleSelection,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange
  } = useListPage<ProductFilterForm, ProductListItem>(
    {
      fetch: params =>
        productApi.fetchList(params as ProductListParams & Record<string, any>)
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: response => ({
        list: response.list ?? [],
        total: response.pagination?.total ?? 0,
        pageSize: response.pagination?.pageSize ?? formState.page_size,
        currentPage: response.pagination?.currentPage ?? formState.page
      })
    }
  );

  const statusOptions = STATUS_OPTIONS;
  const auditStatusOptions = AUDIT_STATUS_OPTIONS;

  const statusTagType = (status: number) => {
    switch (status) {
      case 1:
        return "success";
      case 2:
        return "info";
      case 3:
        return "danger";
      default:
        return "warning";
    }
  };

  const auditStatusTagType = (status: number) => {
    switch (status) {
      case 1:
        return "success";
      case 2:
        return "danger";
      default:
        return "warning";
    }
  };

  const statusLabel = (status: number) => {
    return PRODUCT_STATUS_MAP[status] ?? `状态 ${status}`;
  };

  const auditStatusLabel = (status: number) => {
    return PRODUCT_AUDIT_STATUS_MAP[status] ?? `状态 ${status}`;
  };

  const regionLabelMap = computed(() => {
    const map = new Map<number, string>();
    const traverse = (nodes: Array<any>, parentLabel = "") => {
      nodes.forEach(node => {
        const id = Number(node.id);
        const rawLabel = node.label ?? node.name ?? `区域 ${id}`;
        const currentLabel = parentLabel
          ? `${parentLabel} / ${rawLabel}`
          : rawLabel;
        if (Number.isFinite(id) && id > 0) {
          map.set(id, currentLabel);
        }
        if (Array.isArray(node.children) && node.children.length) {
          traverse(node.children, currentLabel);
        }
      });
    };

    traverse(regionTree.value ?? []);
    return map;
  });

  const deleteProduct = async (id: number) => {
    try {
      await ElMessageBox.confirm("确认删除该商品吗？", "删除确认", {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消"
      });
    } catch {
      return;
    }

    try {
      await productApi.remove(id);
      message("商品已删除", { type: "success" });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "删除商品失败", { type: "error" });
    }
  };

  const batchUpdateStatus = async (status: number) => {
    const ids = multipleSelection.value.map(item => item.id);
    if (ids.length === 0) {
      message("请先选择需要操作的商品", { type: "warning" });
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确认将选中的 ${ids.length} 个商品状态设置为「${statusLabel(status)}」吗？`,
        "批量操作确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await productApi.batchUpdateStatus(ids, status);
      message("状态已更新", { type: "success" });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "更新状态失败", { type: "error" });
    }
  };

  const openProductDialog = (id?: number) => {
    openDialog(() => import("../form.vue"), {
      title: id ? "编辑商品" : "新增商品",
      width: "70%",
      draggable: true,
      fullscreen: false,
      props: {
        id: id ?? null,
        brandOptions: brandOptions.value,
        categoryTree: categoryTree.value,
        regionTree: regionTree.value
      },
      onConfirm: async (_, formRef: any) => {
        if (formRef?.submitForm) {
          const success = await formRef.submitForm();
          if (success) {
            await onSearch();
            return true;
          }
          return false;
        }
        return true;
      }
    });
  };

  const columns: TableColumnList = [
    { type: "selection", width: 48 },
    {
      label: "商品标题",
      prop: "title",
      minWidth: 220,
      align: "left"
    },
    {
      label: "型号",
      minWidth: 180,
      prop: "model",
      align: "left",
    },
    {
      label: "分类",
      prop: "category",
      minWidth: 160,
      formatter: (row: ProductListItem) => row.category?.name ?? "-"
    },
    {
      label: "品牌",
      prop: "brand",
      minWidth: 140,
      formatter: (row: ProductListItem) => row.brand?.name ?? "-"
    },
    {
      label: "价格/库存",
      prop: "default_price",
      minWidth: 140,
      formatter: (row: ProductListItem) =>
        `¥${row.default_price?.toFixed(2)} / ${row.default_stock}`
    },
    {
      label: "状态",
      prop: "status",
      width: 110,
      slot: "status"
    },
    {
      label: "更新时间",
      prop: "update_time",
      width: 180
    },
    {
      label: "操作",
      width: 220,
      fixed: "right",
      slot: "operation"
    }
  ];

  const categoryOptions = computed(() =>
    mapCategoryOptions(categoryTree.value)
  );

  const refreshMeta = async () => {
    const [brands, categories, regions] = await Promise.all([
      productApi.fetchBrandOptions(),
      productApi.fetchCategoryTree(),
      fetchRegionTree()
    ]);
    brandOptions.value = brands;
    categoryTree.value = categories;
    regionTree.value = regions;
  };

  onMounted(async () => {
    await Promise.all([refreshMeta(), onSearch()]);
  });

  return {
    filterForm: formState,
    loading,
    dataList,
    pagination,
    multipleSelection,
    columns,
    statusOptions,
    auditStatusOptions,
    brandOptions,
    regionTree,
    categoryOptions,
    statusTagType,
    statusLabel,
    auditStatusTagType,
    auditStatusLabel,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange,
    openProductDialog,
    deleteProduct,
    batchUpdateStatus
  };
}
